﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MvcWeb.Models;
using SailHero.Soft.FrameWork.IDomainRepositories.Contracts;
using SailHero.Soft.FrameWork.Models;
using UI.Web.SailHeroSoftAuthorization.Helper;

namespace MvcWeb.Controllers
{
    [Export(typeof(IController)), ExportMetadata("Name", "Soft")]
    public class SoftController : BaseController
    {

        /// <summary>
        /// 数据操作接口
        /// </summary>
        [Import]
        public ISoftWareRepository softModel;

        [Import]
        public ISys_UserRepository userModel;

        [Authorize]
        public ActionResult Index(string page)
        {
            var list = softModel.GetAllList();
            list = list.OrderBy(d => d.ORDERNUM);
            int size = 10;
            if (page != null)
            {
                ViewData["page"] = PagerHelper.Pager(Request.RawUrl.Substring(0, Request.RawUrl.IndexOf("?")), Convert.ToInt32(page), list.Count(), size, 4);
                list = list.Skip((Convert.ToInt32(Request["page"]) - 1) * size).Take(size);
            }
            else
            {
                ViewData["page"] = PagerHelper.Pager(Request.RawUrl, 1, list.Count(), size, 4);
                list = list.Skip((1 - 1) * size).Take(size);
            }
            return View(list);
        }

        [Authorize]
        public ActionResult Create()
        {
            ViewData["softList"] = new SelectList(softModel.GetAllList(), "ID", "SoftCName");
            ViewData["userList"] = new SelectList(userModel.GetAllList(), "UserID", "UserCName");
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                SYS_SOFTWARE mod = new SYS_SOFTWARE();
                mod.ID = DateTime.Now.Ticks.ToString();
                mod.SOFTCNAME = Request.Form["SoftCName"];
                mod.SOFTNO = Request.Form["SoftNo"];
                mod.SOFTMANAGER = Request.Form["SoftManager"];
                mod.TELEPHONE = Request.Form["Telephone"];
                mod.PARTENTID = Request.Form["softList"];
                mod.ORDERNUM = string.IsNullOrEmpty(Request.Form["OrderNum"]) ? 999 : Convert.ToInt32(Request.Form["OrderNum"]);
                mod.ISENABLE = Request.Form["isEnable"] == "on" ? "1" : "0";
                mod.CREATOR = LoginUser.USERCNAME;
                mod.CREATEDATE = DateTime.Now;
                mod.DOWNLOADPATH = Request.Form["DownloadPath"];
                softModel.Add(mod);
                softModel.UnitOfWork.SaveChanges();
                return RedirectToAction("Index");

            }
            catch (Exception ee)
            {
                ViewData["softList"] = new SelectList(softModel.GetAllList(), "ID", "SoftCName");
                ViewData["userList"] = new SelectList(userModel.GetAllList(), "UserID", "UserCName");
                return View();
            }
        }

        [Authorize]
        public ActionResult Edit(string id)
        {
            SYS_SOFTWARE mod = softModel.Get(id);
            ViewData["softList"] = new SelectList(softModel.GetAllList(), "ID", "SoftCName", mod.PARTENTID);
            return View(mod);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            SYS_SOFTWARE mod = softModel.Get(id);
            try
            {
                mod.SOFTCNAME = Request.Form["SoftCName"];
                mod.SOFTMANAGER = Request.Form["SoftManager"];
                mod.SOFTNO = Request.Form["SoftNo"];
                mod.TELEPHONE = Request.Form["Telephone"];
                mod.PARTENTID = Request.Form["softList"];
                mod.ORDERNUM = string.IsNullOrEmpty(Request.Form["OrderNum"]) ? 999 : Convert.ToInt32(Request.Form["OrderNum"]);
                mod.ISENABLE = Request.Form["isEnable"] == "false" ? "0" : "1";
                mod.UPDATEUSER = LoginUser.USERCNAME;
                mod.UPDATEDATE = DateTime.Now;
                mod.DOWNLOADPATH = Request.Form["DownloadPath"];
                softModel.UnitOfWork.SaveChanges();

                return RedirectToAction("Index");


            }
            catch (Exception ee)
            {
                ViewData["softList"] = new SelectList(softModel.GetAllList(), "ID", "SoftCName", mod.PARTENTID);
                return View(mod);
            }
        }

        [Authorize]
        [HttpPost]
        public string Delete(string ID)
        {
            try
            {
                // TODO: Add delete logic here
                softModel.Delete(itm => itm.ID == ID);
                softModel.UnitOfWork.SaveChanges();
                return "success";
            }
            catch
            {
                return "fail";
            }
        }


        [HttpPost]
        public void Upload()
        {
            string uploadPath = new PathHelper().GetLocalPath()+"/Upload/";

            string filename = string.Empty;
            string tmpPath = Server.MapPath(uploadPath);
            try
            {
                if (Request.Files["fileToUpload"] != null)
                {

                    filename = Request.Files["fileToUpload"].FileName;
                    if (filename.LastIndexOf("\\") > 0)
                    {
                        filename = filename.Substring(filename.LastIndexOf("\\")).Replace("\\", "");
                    }
                    Stream st = Request.Files["fileToUpload"].InputStream;
                    int size = 0;
                    StreamToFile(st, tmpPath + filename, out size);

                    Response.Clear();
                    Response.Write(@"{
                    status : 'success',
                    msg : '" + uploadPath + filename + @"'
                    }");
                    Response.End();
                }

            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.Write(@"{
                status : 'error',
                msg : '" + ex.Message + @"'
                }");
                Response.End();
            }
        }

        /// <summary> 
        ///  
        /// </summary> 
        /* - - - - - - - - - - - - - - - - - - - - - - - - 
        * Stream 和 文件之间的转换 
        * - - - - - - - - - - - - - - - - - - - - - - - */
        /// <summary>
        /// 将 Stream 写入文件
        /// </summary>
        /// <param name="stream">传入的Stream流对象</param>
        /// <param name="fileName">要存储的完整路径文件名</param>
        /// <param name="fileSize">文件大小</param>
        public static void StreamToFile(Stream stream, string fileName, out int fileSize)
        {
            FileStream fs, targetStream;

            //文件流传输
            using (targetStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                //定义文件缓冲区
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;

                while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                }
                fileSize = (int)targetStream.Length;
                targetStream.Close();
                stream.Close();
            }
        }
    }
}
